package p.ithorns.framework.common.text;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

/**
 * DecimalUtil
 *
 * @author ithorns
 * @version 1.0
 * @date 2020/4/21 15:06
 */
public class DecimalUtil {

    private final static Logger log = LoggerFactory.getLogger(DecimalUtil.class);


    private static final ThreadLocal<DecimalFormat> THREAD_LOCAL =
            ThreadLocal.withInitial(() -> {
                try {
                    NumberFormat f = NumberFormat.getInstance(Locale.getDefault());
                    if (f instanceof DecimalFormat formatter) {
                        formatter.setDecimalSeparatorAlwaysShown(true);
                        //设置舍入模式 为DOWN,否则默认的是HALF_EVEN
                        formatter.setRoundingMode(RoundingMode.DOWN);

                        return formatter;
                    }
                } catch (Exception e) {
                    log.error("DecimalUtil.format error", e);
                }
                return new DecimalFormat();
            });


    public static String format(String regx, double decimal) {
        DecimalFormat formatter = THREAD_LOCAL.get();
        formatter.applyPattern(regx);
        return formatter.format(decimal);
    }

    public static String getPriceStrInfo(String splitDecimal, int count, String inputStr) {
        DecimalFormat decimalFormat = THREAD_LOCAL.get();

        BigDecimal num = new BigDecimal(inputStr);
        decimalFormat.applyPattern("0:0.00");
        String str = decimalFormat.format(num);


        StringBuilder sbuf = new StringBuilder(str);
        if ((str.length() - 3) > count) {
            str = "";
            for (int j = 0; j < count; j++) {
                sbuf.append("9");
            }
            sbuf.append(".99");
        }

        String strValue = sbuf.toString();
        sbuf.delete(0, sbuf.length());


        if (".".equals(splitDecimal)) {
            str = String.format("%.2f", num);
            count += count / 3;
        } else if (",".equals(splitDecimal)) {
            DecimalFormat df = new DecimalFormat("{0:0,0.00}");
            str = df.format(new BigDecimal(strValue));
            count += count / 3;
        } else {
            str = new DecimalFormat("0:0.00").format(new BigDecimal(strValue));
        }

        sbuf.append(str);
        int num2 = sbuf.length() - 3;
        for (int i = 0; i < (count - num2); i++) {
            //str = " " + str;
            sbuf.insert(0, " ");
        }

        return sbuf.toString();
    }

}